<template>
    <div>
        <!-- 遮罩阻止点击别的按钮 -->
        <div v-if="visible" class="custom-dialog-big-background">
            <!-- 自定义弹窗 -->
            <div class="custom-dialog">
                <div class="dialog-backdrop" @click="closeDialog"></div>

                <div class="dialog-container">
                    <div class="dialog-header">
                        <slot name="header">
                            <h3 class="dialog-title">{{ title }}</h3>
                        </slot>
                        <div class="buttons">
                            <img src="../assets/img/module5/dialog/guanbi.png" @click="closeDialog" alt="关闭"
                                class="button-icon" />
                        </div>
                    </div>

                    <div class="dialog-content">
                        <!-- 输入框区域 -->
                        <div class="input-section">
                            <!-- 空域对象 -->
                            <div class="contentWapper">
                                <span class="dialogText">空域对象</span>
                                <el-input v-model="localSelectedObject" placeholder="请输入" class="input-box"
                                    readonly></el-input>
                            </div>

                            <!-- 带背景框的状态和时间选择区域 -->
                            <div class="selection-background">
                                <!-- 空域状态 -->
                                <div class="contentWapper-select">
                                    <span class="dialogText">空域状态</span>
                                    <el-select v-model="localSelectedStatus" placeholder="请选择" class="select-box">
                                        <el-option label="请选择" value=""></el-option>
                                        <el-option label="开启" value="开启"></el-option>
                                        <el-option label="关闭" value="关闭"></el-option>
                                    </el-select>
                                </div>

                                <!-- <div class="contentWapper-select">
                                    <span class="dialogText">开始时段</span>
                                    <el-time-picker v-model="selectedStartTime" placeholder="请选择时间"
                                        value-format="HH:mm:ss" class="select-box"></el-time-picker>
                                </div>

                                <div class="contentWapper-select">
                                    <span class="dialogText">结束时段</span>
                                    <el-time-picker v-model="selectedEndTime" placeholder="请选择时间"
                                        value-format="HH:mm:ss" class="select-box"></el-time-picker>
                                </div> -->
                                <!-- 开始时段 -->
                                <div class="contentWapper-select">
                                    <span class="dialogText">开始时段</span>
                                    <el-date-picker v-model="localSelectedStartTime" type="datetime"
                                        placeholder="请选择日期和时间" value-format="yyyy-MM-dd HH:mm:ss" class="select-box">
                                    </el-date-picker>
                                </div>

                                <!-- 结束时段 -->
                                <div class="contentWapper-select">
                                    <span class="dialogText">结束时段</span>
                                    <el-date-picker v-model="localSelectedEndTime" type="datetime"
                                        placeholder="请选择日期和时间" value-format="yyyy-MM-dd HH:mm:ss" class="select-box">
                                    </el-date-picker>
                                </div>
                            </div>

                            <!-- 容量系数 -->
                            <div class="contentWapper">
                                <span class="dialogText">容量系数</span>
                                <el-input v-model="localCapacityFactor" placeholder="请输入0-1.5之间的值" :disabled="isDisabled" v-loading="loadingCapacity"
                                    @input="validateCapacityFactor" class="input-box">
                                </el-input>
                            </div>

                            <!-- 间隔系数 -->
                            <div class="contentWapper">
                                <span class="dialogText">间隔系数</span>
                                <el-input v-model="localIntervalFactor" placeholder="请输入1-5之间的值" :disabled="isDisabled" v-loading="loadingInterval"
                                    @input="validateIntervalFactor" class="input-box">
                                </el-input>
                            </div>
                        </div>

                        <!-- 按钮 -->
                        <div class="buttonWapper">
                            <!-- <button class="diaButton" @click="cancelDia">计算系数</button> -->
                            <button class="diaButton" @click="closeDialog">取消</button>
                            <button class="diaButton" @click="confirmDia">确定</button>
                        </div>
                    </div>

                    <div class="dialog-footer">
                        <img src="../assets/img/module5/dialog/dialogicon3.png" class="img-foot" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import axios from 'axios';

const baseApi = process.env.NODE_ENV === 'production'
    //? process.env.VUE_APP_REMOTE_API
    ? '/api'  // 使用代理路径
    : process.env.VUE_APP_REMOTE_API_MODULE6;

export default {
    props: {
        visible: Boolean,
        title: String,
        selectedObject: String,
        selectedStatus: String,
        selectedStartTime: String,
        selectedEndTime: String,
        capacityFactor: [String, Number],  // 接受 String 和 Number 类型
        intervalFactor: [String, Number],  // 接受 String 和 Number 类型
        operationId: Number,  // 仅编辑时传递
        objectId: Number      // 新增和编辑时都会传递
    },
    data() {
        return {
            localSelectedObject: this.selectedObject,
            localSelectedStatus: this.selectedStatus,
            localSelectedStartTime: this.selectedStartTime,
            localSelectedEndTime: this.selectedEndTime,
            localCapacityFactor: this.capacityFactor,
            localIntervalFactor: this.intervalFactor,
            isDisabled: false, // 是否禁用输入框
            loadingCapacity: false, // 容量系数加载状态
            loadingInterval: false, // 间隔系数加载状态
            localOperationId: this.operationId,  // 将父组件传入的 operationId 存储
            localObjectId: this.objectId         // 将父组件传入的 objectId 存储
        };
    },
    watch: {
        // 同步 props 和 data，当 props 发生变化时更新 local 值
        selectedObject(newVal) {
            this.localSelectedObject = newVal;
        },
        selectedStatus(newVal) {
            this.localSelectedStatus = newVal;
        },
        selectedStartTime(newVal) {
            this.localSelectedStartTime = newVal;
        },
        selectedEndTime(newVal) {
            this.localSelectedEndTime = newVal;
        },
        capacityFactor(newVal) {
            this.localCapacityFactor = newVal;
        },
        intervalFactor(newVal) {
            this.localIntervalFactor = newVal;
        },
        operationId(newVal) {
            this.localOperationId = newVal;
            console.log("operationId变化为了", newVal)
        },
        objectId(newVal) {
            this.localObjectId = newVal;
            console.log("objectId变化为了", newVal)
        }
    },
    methods: {
        formatDateTime(dateString) {
            // 确保传入的时间是 Date 对象
            const date = new Date(dateString);

            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以需要 +1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            // 返回 ISO 格式的日期和时间字符串
            return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
        },
        closeDialog() {
            // this.$emit("refreshHistory");  // 通知父组件刷新数据
            this.$emit("update:visible", false);  // 关闭弹窗
        },
        cancelDia() {
            console.log("计算系数被点击了");
            // 设置加载状态
            this.loadingCapacity = true;
            this.loadingInterval = true;
            this.isDisabled = true;

            // try {
            //     const response = await axios.get('/api/getFactors'); // 请求后端API
            //     if (response.data.success) {
            //         this.localCapacityFactor = response.data.capacityFactor;
            //         this.localIntervalFactor = response.data.intervalFactor;
            //     } else {
            //         this.$message.error('获取数据失败');
            //         this.isDisabled = false; // 失败时重新启用输入框
            //     }
            // } catch (error) {
            //     this.$message.error('请求失败，请检查网络');
            //     this.isDisabled = false; // 失败时重新启用输入框
            // } finally {
            //     this.loadingCapacity = false;
            //     this.loadingInterval = false;
            // }

            setTimeout(() => {
                // 模拟后端返回数据
                const mockResponse = {
                    success: true,
                    capacityFactor: (Math.random() * 1.5).toFixed(2), // 生成0-1.5之间的随机数
                    intervalFactor: (Math.random() * 4 + 1).toFixed(2) // 生成1-5之间的随机数
                };

                if (mockResponse.success) {
                    this.localCapacityFactor = mockResponse.capacityFactor;
                    this.localIntervalFactor = mockResponse.intervalFactor;
                } else {
                    this.$message.error('获取数据失败');
                    this.isDisabled = false; // 失败时重新启用输入框
                }

                // 关闭加载状态
                this.loadingCapacity = false;
                this.loadingInterval = false;
            }, 1500); // 模拟1.5秒的请求延迟
        },
        async confirmDia() {
            try {
                const requestData = {
                    operationId: this.localOperationId || null,  // 如果没有 operationId 表示是新增
                    objectId: this.localObjectId,               // 新增和编辑时都需要
                    airspaceObjectName: this.localSelectedObject,
                    startStopState: this.localSelectedStatus,
                    capacityThreshold: Number(this.localCapacityFactor),
                    safeIntervalThreshold: Number(this.localIntervalFactor),
                    startTime: this.formatDateTime(this.localSelectedStartTime),
                    endTime: this.formatDateTime(this.localSelectedEndTime)
                };
                console.log("发送的数据:", requestData);

                const response = await axios.post(`${baseApi}/manage/saveorinsert`, requestData);

                if (response.data.code === 0) {
                    console.log("操作成功:", response.data.message);
                    this.$emit("update:visible", false); // 成功后关闭弹窗
                    this.$message.success('操作成功');  // 成功时显示消息
                } else if (response.data.code === 500) {
                    this.$message.error(response.data.message);
                } else {
                    console.error("操作失败:", response.data.message);
                }
            } catch (error) {
                console.error("请求失败:", error);
                this.$message.error('请求失败，请稍后再试');
            }
        },
        // 验证容量系数
        validateCapacityFactor() {
            if (this.localCapacityFactor < 0) {
                this.localCapacityFactor = 0;
            } else if (this.localCapacityFactor > 1.5) {
                this.localCapacityFactor = 1.5;
            }
        },
        // 验证间隔系数
        validateIntervalFactor() {
            if (this.localIntervalFactor < 1) {
                this.localIntervalFactor = 1;
            } else if (this.localIntervalFactor > 5) {
                this.localIntervalFactor = 5;
            }
        },
    },
};
</script>

<style scoped>
.custom-dialog-big-background {
    position: fixed;
    top: 0%;
    left: 0%;
    width: 40%;
    height: 60%;
    background-color: transparent;
    z-index: 9990;
}

/* 弹窗背景 */
.custom-dialog {
    position: fixed;
    top: 50%;
    left: 50%;
    width: 35vw;
    height: 50vh;
    transform: translate(-50%, -50%);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9990;
}


.dialog-container {
    position: relative;
    width: 100%;
    background-image: url("../assets/img/module5/dialog/container.png");
    background-size: cover;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    border-radius: 10px;
    /* 圆角设置 */
}

.dialog-header {
    display: flex;
    width: 100%;
    height: 3rem;
    justify-content: center;
    align-items: center;
    position: relative;
    background-image: url("../assets/img/module5/dialog/headbar.png"), url("../assets/img/module5/dialog/dialogtopimg1.png"), url("../assets/img/module5/dialog/dialogtopimg2.png");
    background-position: center, center, center;
    background-size: cover, auto, cover;
    background-repeat: no-repeat, no-repeat, no-repeat;
    border-top-left-radius: 10px;
    /* 左上角圆角 */
    border-top-right-radius: 10px;
    /* 右上角圆角 */
}

.dialog-title {
    font-size: 1.5rem;
    color: #ffffff;
    text-align: center;
    margin: 0;
}

.buttons {
    position: absolute;
    right: 2%;
}

.button-icon {
    width: 40px;
    height: 40px;
    cursor: pointer;
}

.dialog-content {
    width: 100%;
    margin-top: 2rem;
    margin-bottom: 1rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 15px;
}

.input-section {
    display: flex;
    flex-direction: column;
    width: 90%;
    align-items: center;
    gap: 10px;
}

.contentWapper {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 70%;
    gap: 10px;
}

.contentWapper-select {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 102%;
    gap: 10px;
}

.dialogText {
    font-size: 0.93vw;
    color: #749fbf;
    width: 30%;
    text-align: right;
}

.input-box,
.select-box {
    width: 60%;
    background-color: #0d141b;
    color: #ffffff;
    border-radius: 4px;
}

.selection-background {
    width: 70%;
    /* margin-left: 10%; */
    border: 2px solid #1d405c;
    padding: 10px 10px 10px 0;
    background-color: rgba(13, 20, 27, 0.7);
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.buttonWapper {
    display: flex;
    justify-content: center;
    gap: 20px;
    width: 100%;
    margin-top: 2rem;
}

.diaButton {
    height: 30px;
    width: 120px;
    border: none;
    color: white;
    font-size: 18px;
    background-color: transparent;
    background-image: url('../assets/img/module2/button-tijiao.png');
    background-size: 100% 100%;
    cursor: pointer;
}

.diaButton:hover {
    background-color: rgba(255, 255, 255, 0.1);
    transform: scale(1.05);
}

/* 弹窗底部 */
.dialog-footer {
    display: flex;
    width: 100%;
    height: 2rem;
    margin-bottom: 1rem;
    position: relative;
}

/*右下角标识*/
.img-foot {
    position: absolute;
    right: 2%;
}


/*选择用户输入框颜色*/
.contentWapper /deep/ .el-input--medium .el-input__inner {
    border: 2px solid #1d405c;
    color: #ffffff;
    background-color: #0d141b;
}

.contentWapper /deep/ .el-select-dropdown {
    border: none;
    background: #0d141b;
    z-index: 9991;
}

.contentWapper /deep/ .el-select-dropdown__item {
    background-color: transparent;
    color: #fff;
    z-index: 9991;
}

.contentWapper /deep/ .el-tag.el-tag--info {
    border: none;
    background-color: #1d405c;
    color: #fff;
}

.contentWapper-select /deep/ .el-input--medium .el-input__inner {
    border: 2px solid #1d405c;
    color: #ffffff;
    background-color: #0d141b;
}

.contentWapper-select /deep/ .el-select-dropdown {
    border: none;
    background: #0d141b;
    z-index: 9991;
}

.contentWapper-select /deep/ .el-select-dropdown__item {
    background-color: transparent;
    color: #fff;
    z-index: 9991;
}

.contentWapper-select /deep/ .el-tag.el-tag--info {
    border: none;
    background-color: #1d405c;
    color: #fff;
}
</style>
